<?php

namespace app\controller;

use app\BaseController;
use app\databaseField;
use app\message;
use app\model\CluePerson;
use app\model\CluePersonAllocationRecord;
use app\model\OrderDeal;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderLog;
use app\model\OrderOtherCertificateBusiness;
use app\model\OrderPersonCertificateRegister;
use app\model\SystemBusiness;
use app\model\SystemDynamicFrom;
use app\model\SystemDynamicFromField;
use app\model\SystemFieldPower;
use app\model\UnitInfo;
use app\model\User;
use app\Request;
use app\service\Certificate;
use app\service\From;
use app\service\RedisService;
use app\service\System;
use think\console\command\make\Validate;
use think\facade\Db;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Log;
use GatewayClient\Gateway;

class CertificateRegister extends BaseController
{
    private $regUnit = 3;//注册单位
    private $employUnit = 2;//聘用单位
    private $pushUnit = 1;//出证单位

    //根据提交参数判断重定向地址

    /**
     * 证书注册
     * 证书办理
     * 企业证书
     */

    /***********************************************************证书注册***************************************************************/

    //获取人才证书注册表单
    public function getPersonCertificateRegisterForm(
        Request $request,
        System $system,
        SystemDynamicFrom $from,
        \app\service\User $userService,
        SystemDynamicFromField $systemDynamicFromField,
        SystemFieldPower $systemFieldPower,
        User $user
    ){
        $aliasId = $request->get('aliasId');

        if (empty($aliasId)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //获取该模板id
        $fromId = $from->getFromId($aliasId);

        //获取当前用户字段权限
        $fieldData = $userService->userFieldPower ($user,$fromId,$request->get ('user_login_id'));

        //获取模板自定义字段详情
        $fieldList = $systemDynamicFromField->getTmpTrendsFieldList($fromId);

        //获取模板字段权限id
        $data = $system->powerPoint($fieldList,array_values($fieldData),true);

//        databaseField::$zszc_from['custom'] = $data;  //动态表单内容 静态表单内容拼接

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$data);
    }

    //附属业务类型列表
    public function subsidiaryBusiness(SystemBusiness $business)
    {
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$business->getSubsidiaryBusinessListModel());
    }

    //人才证书注册提交
    public function addRegisterCertificate(
        Request                        $request,
        Certificate                    $certificate,
        CluePerson                     $person,
        OrderPersonCertificateRegister $orderReg,
        OrderOtherCertificateBusiness  $orderBs,
        User  $user,
        OrderLog  $orderLog,
        Gateway $gateway,
        \app\model\UserMessage $message,
        Certificate $certificateSer,
        Image $image
    ){
        $param = $request->post ();
        $uid = $request->param ('user_login_id');

        //拆分证书
        $param = $certificateSer->splitCer($request->post());

//        $information_file = $request->file('information_file');
//        $contract_file = $request->file('contract_file');

        $param['certificate_code'] = $certificate->CertificateCodeCreate ();
        //提交人id
        $param['submit_id'] = $request->param ('user_login_id');
        //收证部门收证人
        $param['get_uid'] = $request->param ('user_login_id');
        $param['get_org'] = $user->getUidOrgId($request->param ('user_login_id'));

        //基本参数验证
        try {
//            Validate(\app\validate\Certificate::class)->scene ('addCertificateRegister')->check ($param);
//
//            Validate(\app\validate\Certificate::class)->scene ('file')->check ([
//                'information_file'=>$information_file,
////                'contract_file'=>$contract_file
//            ]);
//            //判断人才库人才数据归属权
//            //查询人才基本信息
            //判断人才库人才数据归属权
            //查询人才基本信息
            $personInfo = $person->getPersonIdCardInfo($param['person_id_card']);

//            //如果人才不存在 return false
            if (!$person->getPersonIdCard($param['person_id_card'])){
                return ReJson (message::$ERROR_CODE,message::$ERR_PERSON_ID_CARD_REPEAT);
            }
//            //如果人才负责人不是当前提交人 return false
//            print_r ($request->param ('user_login_id'));die;
            if (!empty($personInfo['f_uid'])){
                if ($personInfo['f_uid']['id'] != $request->param ('user_login_id')){
                    return ReJson (message::$ERROR_CODE,message::$ERR_PERSON_FUID_NEQ);
                }
            }

            //开启事务
            Db::startTrans();
            $str = '';
            //是否有附加证书办理业务
            if (isset($param['ancillary'])){
                $param['ancillary'] = json_decode ($param['ancillary'], true);

                //循环添加证书办理
                $file = '';
                $file2 = '';

                foreach ($param['ancillary'] as $index => &$items) {
                    $file = $request->file('information_file');
                    $file2 = $request->file('contract_file');

                    Validate(\app\validate\Certificate::class)->scene ('file')->check ([
                        'information_file'=> $file,
                        'contract_file' =>$file2
                    ]);
                    //上传资料
                    if (!empty($file)){
                        $item['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $file);
                    }
                    //上传合同
                    if (!empty($file2)){
                        $item['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $file2);
                    }

                    //拆分证书
                    $item = $certificateSer->splitCer($items);

                    //部门处理
                    $item['get_uid'] = $uid;
                    $item['get_org'] = $user->getUidOrgId($uid);

                    //计算业绩
                    if (isset($item['sale_price'], $item['cost_price'])){
                        $item['performance'] = $item['sale_price']-$item['cost_price'];
                    }
                    //业绩归属人
                    $item['performance_uid'] = $item['get_uid'];
                    //处理文件路径
                    $strs = "file/";
                    if ($item['contract_file']){
//                        $item['contract_file'] = strstr($item['contract_file'],$strs);
                        $array = $image->handle($item['contract_file'],'contract_file','contract_file_name');
                        $item['contract_file'] = $array['contract_file'];
                        $item['contract_file_name'] = $array['contract_file_name'];
                    }
                    if ($item['information_file']){
//                        $item['information_file'] = strstr($item['information_file'],$strs);
                        $array = $image->handle($item['information_file'],'information_file','information_file_name');
                        $item['information_file'] = $array['information_file'];
                        $item['information_file_name'] = $array['information_file_name'];
                    }

                    $item['submit_id'] = $uid; //提交人
                    $item['certificate_code'] = $certificate->CertificateCodeCreate ('ZSBL'); //证书id

                    //添加证书办理
                    //循环添加 获取自增id
                    $subData= $orderBs->addData($item);

                    $str .= $subData->id.',';

                    /**
                     * 添加订单日志
                     */
                    $orderLog->addDataModel([
                        'submit_id'=>$uid,
                        'message'=>message::$ORDER_SHENGCHENG,
                        'type'=>1,
                        'order_company_id'=>$subData->id,
                        'certificate_code'=>$item['certificate_code']
                    ]);

                    //添加附加业务消息提醒
                    $messages = $message->addOrderHandleModel($subData['certificate_code'],$subData['responsibility_uid'],$uid,$subData['id']);
                    //发送用户提醒
                    $gateway->sendToUid($subData['responsibility_uid'],json_encode($messages));
                }
            }


            //上传资料
            if (isset($param['information_file'])){
                //$param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);
                $array = $image->handle($param['information_file'],'information_file','information_file_name');
                $param['information_file'] = $array['information_file'];
                $param['information_file_name'] = $array['information_file_name'];
            }
            //上传合同
            if (isset($param['contract_file'])){
//                $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
                $array = $image->handle($param['contract_file'],'contract_file','contract_file_name');
                $param['contract_file'] = $array['contract_file'];
                $param['contract_file_name'] = $array['contract_file_name'];
            }

            $param['ancillary_businesses_id'] = rtrim ($str,',');

            //查询数据库是否已经存在同身份证号码 同证书信息
            if($orderReg->getPersonIdCardCerOrderModel ($param['person_id_card'],$param['certificate_zhuanye'])){
                //为了保证退单到期唯一性
                return ReJson (message::$ERROR_CODE,'存在相同证书订单,请修改后提交');
            }
            //添加注册证书
            $idData = $orderReg->addCerRegisterModel ($param);

            //添加操作日志
            $orderLog->addDataModel([
                'submit_id'=>$uid,
                'message'=>message::$ORDER_PERSON_ADD,
                'type'=>1,
                'order_company_id'=>$idData['id'],
                'certificate_code'=>$idData['certificate_code']
            ]);

            //修改人才分配人信息
            $person->editPersonModel(['id'=>$personInfo['id'],'f_uid'=>$request->param ('user_login_id')]);

            //添加消息提醒
            $messages = $message->addCertificateExamineModel($idData['certificate_code'],$idData['responsibility_uid'],$uid,$idData['id']);

            //发送用户提醒
            $gateway->sendToUid($idData['responsibility_uid'],json_encode($messages));

            Db::commit();
        }catch (ValidateException | \Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }

    //企业证书注册提交
    public function addRegEnterpriseCertificate(
        Request                            $request,
        OrderEnterpriseCertificateRegister $certificateRegister,
        Certificate                        $certificate,
        UnitInfo                           $unit,
        User $user,
        OrderLog $orderLog,
        Certificate $certificateSer,
        OrderDeal $dealModel,
        SystemBusiness $businessModel
    ){
        $param = $certificateSer->splitCer($request->post());
        $businId = 0;
        //公示栏默认值
        if ($param['business_id'] == '证书匹配'){
           $param['business_id'] = $businessModel->getBusinessIdModel ('证书匹配');
           $businId = '证书匹配';
        }

        //证书编号
        $param['certificate_code'] = $certificate->CertificateCodeCreate ('QYZSZC');

//        $param['submit_id'] = $request->param ('user_login_id');

        //公示栏与资料部
        $type = explode(',',$param['type']);
        if (count($type) == 2){
            $param['type'] = $type[0] + $type[1];
        }else{
            $param['type'] = $type[0];
        }


        //收证部门收证人
        $param['get_uid'] = $param['submit_id'] = $request->param ('user_login_id')?:0;


        $param['get_org'] = $user->getUidOrgId($request->param ('user_login_id'))?:0;

        Db::startTrans();

        try {
            if ($businId == '证书匹配'){
                Validate(\app\validate\Certificate::class)->scene ('PublicAddEnter')->check ($param);
            }else{
                Validate(\app\validate\Certificate::class)->scene ('addEnRegCertificate')->check ($param);
            }

            //判断是否提交注册单位
            if (!empty($param['reg_unit'])){

                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['reg_unit'],
                    'type'=>$this->regUnit
                ]);
            }
            //判断是否提交注册单位
            if (!empty($param['unit_reg_title'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['unit_reg_title'],
                    'type'=>$this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])){
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['employ_unit_title'],
                    'contacts'=>$param['employ_unit_name'],
                    'mobile'=>$param['employ_unit_mobile'],
                    'type'=>$this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])){
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['out_org'],
                    'type'=>$this->pushUnit
                ]);
            }

            //人数默认1
            if (!isset($param['people_num'])){
                $param['people_num'] = 1;
            }

            $idData = $certificateRegister->addRegCertificateModel ($param);

            //添加操作日志
            $orderLog->addDataModel([
                'submit_id'=>$param['submit_id'],
                'message'=>message::$ORDER_SHENGCHENG,
                'type'=>1,
                'order_company_id'=>$idData['id'],
                'certificate_code'=>$idData['certificate_code']
            ]);
            //添加成交库
            //续出状态
            $dealModel->addOrderDataModel ([
                'order_company_id'=>$idData->id,
                'certificate_code'=>$param['certificate_code'],
                'status'=>2
            ]);

            Db::commit();
        }catch (ValidateException | \Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }


    //证书注册续签
    public function postRenewal(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        Certificate                        $certificateSer,
        OrderEnterpriseCertificateRegister $register,
        CluePerson $person,
        CluePersonAllocationRecord $allocationRecord,
        OrderLog $log,
        UnitInfo $unit,
        OrderDeal $dealModel,
        \app\service\Order $orderSer,
        Image $image,
        RedisService $redisService
    ){
        $param = $certificateSer->splitCer ($request->post ());
        $uid = $request->param ('user_login_id');

        Db::startTrans();
        try {
            //查询原订单
            $original = $company->getIdCertificateCodeFindModel($param['id'],$param['certificate_code']);

            if (!$original){
                return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
            }

            if ($original['status']['id'] != 1 && $original['status']['id'] != 2){
                return ReJson (message::$ERROR_CODE,message::$CERTIFICATE_XUQIAN_STATUS_ERR);
            }

            //生成证书编码
            $code = $certificateSer->CertificateCodeCreate ('QYZSZC');
            Db::startTrans();
            try {
                //添加证书注册表
                $regData['certificate_leixing'] = $param['certificate_leixing'];
                $regData['certificate_leibie'] = $param['certificate_leibie'];
                $regData['certificate_dengji'] = $param['certificate_dengji'];
                $regData['certificate_zhuanye'] = $param['certificate_zhuanye'];
                $regData['certificate_id'] = $param['certificate_id'];
                $regData['business_id'] = $param['business_id'];

                $regData['certificate_code'] = $code;

                $regData['sale_org'] = $param['sale_org'];
                $regData['sale_uid'] = $param['sale_uid'];
                $regData['reg_unit'] = $param['reg_unit'];
                $regData['price_unit'] = $param['price_unit'];
                $regData['certificate_b'] = $param['certificate_b'];
                $regData['social_security'] = $param['social_security'];
                $regData['cycle'] = $param['cycle'];
                $regData['project'] = $param['project'];
                $regData['people_num'] = 0;
                $regData['type'] = 1;
                $regData['submit_id'] = $uid;
                //证书需求表
                $regCreate = $register->addRegCertificateModel ($regData);

                //添加证书注册补充表
                //生成证书编码
                $code2 = $certificateSer->CertificateCodeCreate ('QYZSZC');

                $comData['certificate_leixing'] = $param['certificate_leixing'];
                $comData['certificate_leibie'] = $param['certificate_leibie'];
                $comData['certificate_dengji'] = $param['certificate_dengji'];
                $comData['certificate_zhuanye'] = $param['certificate_zhuanye'];
                $comData['certificate_id'] = $param['certificate_id'];
                $comData['business_id'] = $param['business_id'];
                $comData['sale_org'] = $param['sale_org'];
                $comData['sale_uid'] = $param['sale_uid'];
                $comData['reg_unit'] = $param['reg_unit'];
                $comData['price_unit'] = $param['price_unit'];
                $comData['certificate_b'] = $param['certificate_b'];
                $comData['social_security'] = $param['social_security'];
                $comData['cycle'] = $param['cycle'];
                $comData['project'] = $param['project'];
                $comData['people_num'] = 0;
                $comData['type'] = 1;
                $comData['submit_id'] = $uid;

                $comData['certificate_code'] = $code2;
                $comData['enter_certificate_code'] = $code;
                $comData['enter_id'] = $regCreate->id;
                $comData['get_uid'] = $param['get_uid'];
                $comData['get_org'] = $param['get_org'];
                $comData['contract_price'] = $param['contract_price'];
                $comData['person_id_card'] = $param['person_id_card'];
                $comData['person_name'] = $param['person_name'];
                $comData['reg_from_illustrate'] = $param['reg_from_illustrate'];
                $array = $image->handle($param['reg_from_file'],'reg_from_file','reg_from_file_name');
                $comData['reg_from_file'] = $array['reg_from_file'];
                $comData['reg_from_file_name'] = $array['reg_from_file_name'];
                $comData['responsibility_uid'] = $param['responsibility_uid'];
                $comData['employ_unit_title'] = $param['employ_unit_title'];
                $comData['employ_unit_name'] = $param['employ_unit_name'];
                $comData['employ_unit_mobile'] = $param['employ_unit_mobile'];
                $comData['sale_date'] = date('Y-m-d H:i:s');

                //续签证书改为已售出
                $comData['status'] = 1;

                //业绩归属人
                $comData['performance_uid'] = $param['get_uid'].','.$param['sale_uid'];
                $comData['performance'] = $param['price_unit']-$param['contract_price'];
                $comData['submit_id'] = $uid;

                //添加证书内容
                $idData = $company->addDataModel($comData);

                //添加订单日志
                $log->addDataModel ([
                    'submit_id'=>$uid,
                    'message'=>message::$ORDER_ENPER_DZ_CJ,
                    'type'=>1,
                    'order_company_id'=>$idData['id'],
                    'certificate_code'=>$comData['certificate_code']
                ]);

                //原订单改为已续签
                $idDatas = $company->setXuQianModel($param['id'],$param['certificate_code']);
                $d = $company->getIdCertificateCodeFindModel ($param['id'],$param['certificate_code']);
                $redisService->delOrderDzData ($d,'order_gszs');
                //删除业绩总表缓存
                $redisService->delPerformance ($d);
                //添加订单日志
                $log->addDataModel ([
                    'submit_id'=>$uid,
                    'message'=>message::$ORDER_XUQIAN,
                    'type'=>1,
                    'order_company_id'=>$param['id'],
                    'certificate_code'=>$param['certificate_code']
                ]);

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return ReJson (message::$ERROR_CODE,$e->getMessage ());
            }


            //判断是否提交注册单位
            if (!empty($param['reg_unit'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['reg_unit'],
                    'type'=>$this->regUnit
                ]);
            }
            //判断是否提交注册单位
            if (!empty($param['unit_reg_title'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['unit_reg_title'],
                    'type'=>$this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])){
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['employ_unit_title'],
                    'contacts'=>$param['employ_unit_name'],
                    'mobile'=>$param['employ_unit_mobile'],
                    'type'=>$this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])){
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['out_org'],
                    'type'=>$this->pushUnit
                ]);
            }

            //添加订单日志
            $log->addDataModel([
                'submit_id'=>$uid,
                'message'=>message::$ORDER_XUQIAN,
                'type'=>1,
                'order_company_id'=>$idData['id'],
                'certificate_code'=>$comData['certificate_code']
            ]);

            //修改人才状态为续签
            $person->setIdCardStatusModel ($param['person_id_card']);

            //添加成交库
            //续出状态
            $b_reg_electronic_certificate_date = '';
            if (isset($param['b_reg_electronic_certificate_date'])){
                $b_reg_electronic_certificate_date = $param['b_reg_electronic_certificate_date'];
            }
            $dealModel->addOrderDataModel ([
                'order_company_id'=>$idData->id,
                'certificate_code'=>$idData->certificate_code,
                'status'=>2,
                'b_reg_electronic_certificate_date'=>$b_reg_electronic_certificate_date
            ]);

            //添加人才生命周期
            $personData = $person->getPersonIdCardInfo($param['person_id_card']);
            if(!empty($personData)){
                $allocationRecord->addPersonAllocationModel ($personData['id'],message::$SUCC_PERSON_RENEWAL,$uid);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_PERSON_RENEWAL);
    }

    //倒证续签
    public function postDzRenewal(
        Request                            $request,
        Certificate                        $certificateSer,
        OrderEnterpriseCertificateRegister $register,
        CluePerson $person,
        CluePersonAllocationRecord $allocationRecord,
        OrderLog $log,
        UnitInfo $unit,
        OrderEnterpriseExchange $exchangeModel,
        Image $image,
        OrderDeal $dealModel,
        RedisService $redisService
    ){
        $param = $certificateSer->splitCer ($request->post ());
        $uid = $request->param ('user_login_id');

        Db::startTrans();
        try {

            //查询原订单
            $original = $exchangeModel->getWhereCerDataModel($param['certificate_code']);

            if (!$original){
                return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
            }

            if ($original['status']['id'] != 1 && $original['status']['id'] != 2){
                return ReJson (message::$ERROR_CODE,message::$CERTIFICATE_XUQIAN_STATUS_ERR);
            }

            //生成证书编码
            $code = $certificateSer->CertificateCodeCreate ('QYDZ');

            //添加证书注册表
            $regData['certificate_leixing'] = $param['certificate_leixing'];
            $regData['certificate_leibie'] = $param['certificate_leibie'];
            $regData['certificate_dengji'] = $param['certificate_dengji'];
            $regData['certificate_zhuanye'] = $param['certificate_zhuanye'];
//            $regData['business_id'] = $param['business_id'];
            $regData['certificate_id'] = $param['certificate_id'];

            $regData['certificate_code'] = $code;

            $regData['people_num'] = 0;
            $regData['type'] = 2;
            $regData['dz_status'] = 1;
            $regData['submit_id'] = $uid;

            $regCreate = $register->addRegCertificateModel ($regData);

            //添加证书注册补充表
            $comData['certificate_code'] = $code;
            $comData['enter_certificate_code'] = $regData['certificate_code'];
            $comData['employ_unit_type'] = $param['employ_unit_type'];
            $comData['certificate_id'] = $param['certificate_id'];
            $comData['certificate_leixing'] = $param['certificate_leixing'];
            $comData['certificate_leibie'] = $param['certificate_leibie'];
            $comData['certificate_dengji'] = $param['certificate_dengji'];
            $comData['certificate_zhuanye'] = $param['certificate_zhuanye'];
            $comData['employ_unit_title'] = $param['employ_unit_title'];
            $comData['employ_unit_name'] = $param['employ_unit_name'];
            $comData['employ_unit_mobile'] = $param['employ_unit_mobile'];
            $comData['unit_reg_title'] = $param['unit_reg_title'];
            $comData['out_uid'] = $param['out_uid'];
            $comData['out_org'] = $param['out_org'];
            $comData['out_price'] = $param['out_price'];
            $comData['notice_org'] = $param['notice_org'];
            $comData['notice_id'] = $param['notice_id'];
            $comData['out_unit'] = $param['out_unit'];
            $comData['out_name'] = $param['out_name'];
            $comData['out_mobile'] = $param['out_mobile'];
            $comData['certificate_b'] = $param['certificate_b'];
            $comData['social_security'] = $param['social_security'];
            $comData['cycle'] = $param['cycle'];
            $comData['project'] = $param['project'];
            $comData['transfer'] = $param['transfer'];
            $comData['get_uid'] = $param['get_uid'];
            $comData['get_org'] = $param['get_org'];
            $comData['get_price'] = $param['get_price'];

            $comData['person_name'] = $param['person_name'];
            $comData['id_card'] = $param['id_card'];
            $comData['reg_from_illustrate'] = $param['reg_from_illustrate'];
            $array = $image->handle($param['reg_file'],'reg_file','reg_file_name');
            $comData['reg_file_name'] = $array['reg_file_name'];
            $comData['reg_file'] = $array['reg_file'];
            $comData['contract_illustrate'] = $param['contract_illustrate'];
//            $comData['info_file_name'] = $param['info_file_name'];
//            $comData['info_file'] = $param['info_file'];
            $array = $image->handle($param['info_file'],'info_file','info_file_name');
            $comData['info_file_name'] = $array['info_file_name'];
            $comData['info_file'] = $array['info_file'];
            $comData['other_file_name'] = $param['other_file_name'];
//            $comData['sale_date'] = $param['sale_date'];
            $comData['sale_date'] = date('Y-m-d H:i:s');
            $comData['other_file'] = $param['other_file'];
            $comData['enter_id'] = $regCreate->id;
            $comData['status'] = 1;

            //业绩归属人
            $comData['performance_uid'] = $param['get_uid'].','.$param['out_uid'];
            $comData['performance'] = $param['out_price']-$param['get_price'];
            $comData['submit_id'] = $uid;


            Db::startTrans();
            try {
                //添加证书内容
                $idData = $exchangeModel->addDataModel($comData);
                //添加订单日志
                $log->addDataModel ([
                    'submit_id'=>$uid,
                    'message'=>message::$ORDER_ENPER_DZ_CJ,
                    'type'=>1,
                    'order_company_id'=>$idData['id'],
                    'certificate_code'=>$idData['certificate_code']
                ]);

                //原订单改为已续签
                $idDatas = $exchangeModel->setXuQianModel($param['id'],$param['certificate_code']);
                /**
                 * 修改缓存
                 */
                //查询原订单状态
                $cData = $exchangeModel->getFinanceFieldFindModel ($param['certificate_code']);
                //删除订单表缓存
                $redisService->delOrderDzData ($cData, "order_dz");
                //删除业绩总表缓存
                $redisService->delPerformance ($cData);

                //添加订单日志
                $log->addDataModel ([
                    'submit_id'=>$uid,
                    'message'=>message::$ORDER_XUQIAN,
                    'type'=>1,
                    'order_company_id'=>$param['id'],
                    'certificate_code'=>$param['certificate_code']
                ]);

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return ReJson (message::$ERROR_CODE,$e->getMessage ());
            }

            //判断是否提交注册单位
            if (!empty($param['reg_unit'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['reg_unit'],
                    'type'=>$this->regUnit
                ]);
            }
            //判断是否提交注册单位
            if (!empty($param['unit_reg_title'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['unit_reg_title'],
                    'type'=>$this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])){
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['employ_unit_title'],
                    'contacts'=>$param['employ_unit_name'],
                    'mobile'=>$param['employ_unit_mobile'],
                    'type'=>$this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])){
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['out_org'],
                    'type'=>$this->pushUnit
                ]);
            }

            //添加订单日志
            $log->addDataModel([
                'submit_id'=>$uid,
                'message'=>message::$ORDER_XUQIAN,
                'type'=>1,
                'order_company_id'=>$idData['id'],
                'certificate_code'=>$idData['certificate_code']
            ]);

            //修改人才状态为续签
            $person->setIdCardStatusModel ($param['id_card']);

            //添加成交库
            //续出状态
            $dealModel->addOrderDataModel ([
                'order_company_id'=>$idData->id,
                'certificate_code'=>$code,
                'status'=>2,
                'b_reg_electronic_certificate_date'=>$param['b_reg_electronic_certificate_date']
            ]);

            //修改人才状态为续签
            $person->setIdCardStatusModel ($param['id_card']);

            //添加人才生命周期
            $personData = $person->getPersonIdCardInfo($param['id_card']);
            if (!empty($personData)){
                $allocationRecord->addPersonAllocationModel ($personData['id'],message::$SUCC_PERSON_RENEWAL,$uid);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_RENEWAL);
    }


    //企业倒证
    public function addExchangeCertificate(
        Request                            $request,
        OrderEnterpriseCertificateRegister $reg,
        Certificate                        $certificate,
        UnitInfo                           $unit,
        OrderEnterpriseExchange            $exchangeReg,
        User $user,
        \app\model\UserMessage $message,
        Gateway $gateway,
        OrderLog $orderLog,
        OrderDeal $orderDeal,
        \app\service\User $userService
    ){
       /* sleep (10);
        die;*/
        $param = $request->post ();

        $uid = $request->param ('user_login_id');

        $param['certificate_code'] = $certificate->CertificateCodeCreate ('QYDZ');

        //收证部门收证人
//        $param['get_uid'] = $uid;
//        $param['get_org'] = $user->getUidOrgId($uid)?:0;

        Db::startTrans();
        try {
            Validate(\app\validate\Certificate::class)->scene ('exchangeCertificate')->check ($param);

            //判断是否提交注册单位
            if (!empty($param['reg_unit'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['reg_unit'],
                    'type'=>$this->regUnit
                ]);
            }
            //判断是否提交注册单位
            if (!empty($param['unit_reg_title'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['unit_reg_title'],
                    'type'=>$this->regUnit
                ]);
            }
            //判断是否提交注册单位
            if (!empty($param['unit_reg_title'])){
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['unit_reg_title'],
                    'type'=>$this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])){
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['employ_unit_title'],
                    'contacts'=>$param['employ_unit_name'],
                    'mobile'=>$param['employ_unit_mobile'],
                    'type'=>$this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])){
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel ([
                    'title'=>$param['out_org'],
                    'type'=>$this->pushUnit
                ]);
            }

            //计算业绩
            if (isset($param['out_price'], $param['get_price'])){
                $param['performance'] = $param['out_price']-$param['get_price'];
            }
            if ($param['notice_id']){
                //业绩归属人
                $param['performance_uid'] = $uid.','.$param['notice_id'];
            }

            //提交人
            $param['submit_id'] = $uid;

            //删除param id
            if (isset($param['id'])){
                $id = $param['id'];
                unset($param['id']);

                //查询人数是否满足出售条件
                $regFind = $reg->getWhereIdDataModel($id);

                //生成倒证记录，人数减一
                if ($regFind){
                    if ($regFind['people_num']  < 1){
                        return ReJson (message::$ERROR_CODE,message::$ORDER_DEAL_NUM_MEET);
                    }
                }else{
                    return ReJson (message::$ERROR_CODE,message::$ORDER_DEAL_NUM_MEET);
                }
                $reg->peopleNumDecModel($id);

            }

            //添加企业证书库
            $result = $reg->addRegCertificateModel ([
                'certificate_code'=>$param['certificate_code'],
                'type'=>2,
                'dz_status'=>1
            ]);

            $param['enter_id'] = $result->id;

            $param['sale_date'] = date('Y-m-d H:i:s');
            //添加资料到倒证库
            $data = $exchangeReg->addDataModel ($param);

            //添加操作日志
            $orderLog->addDataModel([
                'submit_id'=>$uid,
                'message'=>message::$ORDER_ENPER_DZ_CJ,
                'type'=>1,
                'order_company_id'=>$data['id'],
                'certificate_code'=>$param['certificate_code']
            ]);

            //添加成交库
            $orderDeal->addOrderDataModel([
                'order_company_id'=>$data['id'],
                'certificate_code'=>$data['certificate_code']
            ]);
            //添加消息列表
            $messages = $message->addOrderExchangeModel($data['certificate_code'],$data['notice_id']['id'],$uid,$data['id']);

            //发送消息通知
            $gateway->sendToUid($data['notice_id']['id'],json_encode ($messages));

            //发送全局成交
            $gateway->sendToAll(json_encode([
                'type'=>'deal',
                'content'=>$userService->getUidOrgTitle ($uid),
                'nickname'=>$user->getIdNickName($uid),
                'title'=> date('Y-m-d H:i:s')."成交了倒证！"
            ]));
            Db::commit();
        }catch (ValidateException | \Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }

    /***********************************************************证书办理***************************************************************/

    //获取人才证书办理表单
    public function getPersonCertificateHandleFrom(
        Request $request,
        System $system,
        SystemDynamicFrom $from,
        \app\service\User $userService,
        SystemDynamicFromField $systemDynamicFromField,
        SystemFieldPower $systemFieldPower,
        User $user
    ){
        $aliasId = $request->get('aliasId');

        if (empty($aliasId)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //获取该模板id
        $fromId = $from->getFromId($aliasId);

        //获取当前用户字段权限
        $fieldData = $userService->userFieldPower ($user,$fromId,$request->get ('user_login_id'));

        //获取模板自定义字段详情
        $fieldList = $systemDynamicFromField->getTmpTrendsFieldList($fromId);

        //获取模板字段权限id
        $data = $system->powerPoint($fieldList,array_values($fieldData),true);

        databaseField::$zsbl_from['custom'] = $data;

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$data);

    }

    //证书办理提交
    public function addHandleCertificate(
        Request                       $request,
        Certificate                   $certificate,
        CluePerson                    $person,
        OrderOtherCertificateBusiness $orderBs,
        User $user,
        Gateway $gateway,
        \app\model\UserMessage $message,
        OrderLog $orderLog,
        Certificate $certificateSer,
        UnitInfo $unit,
        Image $image
    ){
        $uid = $request->param ('user_login_id');
//        $information_file = request()->file('information_file');
//        $contract_file = request()->file('contract_file');
        $param['sale_date'] = '';
        //拆分证书
        $param = $certificateSer->splitCer($request->post());

        //部门处理
        $param['get_uid'] = $uid;
        $param['get_org'] = $user->getUidOrgId($uid);

//        if (isset($param['get_org'])){
//            $get_org = explode (',',$param['get_org']);
//            $param['get_org'] = $get_org[count($get_org)-1];
//        }
//        if (isset($param['out_org'])){
//            $out_org = explode (',',$param['out_org']);
//            $param['out_org'] = $out_org[count($out_org)-1];
//        }

//        Log::error ($param);

        //判断是否提交注册单位
        if (!empty($param['reg_unit'])){
            //注册单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['reg_unit'],
                'type'=>$this->regUnit
            ]);
        }
        //判断是否提交注册单位
        if (!empty($param['unit_reg_title'])){
            //注册单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['unit_reg_title'],
                'type'=>$this->regUnit
            ]);
        }
        //判断是否提交聘用单位
        if (!empty($param['employ_unit_title'])){
            //聘用单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['employ_unit_title'],
                'contacts'=>$param['employ_unit_name'],
                'mobile'=>$param['employ_unit_mobile'],
                'type'=>$this->employUnit
            ]);
        }

        //判断是否提交出证单位
        if (!empty($param['out_org'])){
            //出证单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['out_org'],
                'type'=>$this->pushUnit
            ]);
        }

        //计算提交业绩
        $param['performance'] = (int)$param['sale_price']-(int)$param['cost_price']?:0;

        //业绩归属人
        $param['performance_uid'] = $uid;

        // 启动事务
        Db::startTrans();
        try {
            
            Validate(\app\validate\Certificate::class)->scene ('handleCertificate')->check ($param);

//            Validate(\app\validate\Certificate::class)->scene ('file')->check ([
//                'information_file'=>$information_file,
//                'contract_file'=>$contract_file
//            ]);

            if($param['submit_type'] == 1){
                //判断人才库人才数据归属权
                //查询人才基本信息
                $personInfo = $person->getPersonIdCardInfo($param['person_id_card']);
                if($param['get_uid'] == 1){
                    //如果人才不存在 return false
                    if (!$person->getPersonIdCard($param['person_id_card'])){
                        return ReJson (message::$ERROR_CODE,message::$ERR_PERSON_ID_CARD_REPEAT);
                    }
                }
                //如果人才负责人不是当前提交人 return false
                if (!empty($personInfo['f_uid']['id']) && $personInfo['f_uid']['id'] !=0){
                    if ($personInfo['f_uid']['id'] != $uid){
                        return ReJson (message::$ERROR_CODE,message::$ERR_PERSON_FUID_NEQ);
                    }
                }
            }

            $param['certificate_code'] = $certificate->CertificateCodeCreate ('ZSBL');

            //上传资料
            if (isset($param['information_file'])){
//                $param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);

                $array = $image->handle($param['information_file'],'information_file','information_file_name');
                $param['information_file'] = $array['information_file'];
                $param['information_file_name'] = $array['information_file_name'];
            }
            //上传合同
            if (isset($param['contract_file'])){
//                $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
                $array = $image->handle($param['contract_file'],'contract_file','contract_file_name');
                $param['contract_file'] = $array['contract_file'];
                $param['contract_file_name'] = $array['contract_file_name'];
            }


            $param['submit_id'] = $uid;

            //添加证书办理
            $data = $orderBs->addData($param);
            //修改人才分配人信息
//            $personInfo['f_uid'] = $request->post ('user_login_id');
//            Log::error ($personInfo);

//            $person->editPersonModel(['id'=>$personInfo['id'],'f_uid'=>$uid]);

            //添加操作日志
            $orderLog->addDataModel([
                'submit_id'=>$param['submit_id'],
                'message'=>message::$ORDER_SHENGCHENG,
                'type'=>1,
                'order_company_id'=>$data['id'],
                'certificate_code'=>$data['certificate_code']
            ]);

            //添加消息列表
            $messages = $message->addOrderHandleModel($data['certificate_code'],$data['responsibility_uid'],$uid,$data['id']);
            //发送消息推送
            $gateway->sendToUid($data['responsibility_uid'],json_encode($messages));
            // 提交事务
            Db::commit();
        }catch (ValidateException | \Exception $e){
            // 回滚事务
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }


    /***********************************************************企业证书***************************************************************/
    //获取证书分类下拉框
    public function getEnterSelect(SystemBusiness $business,System $system)
    {
        $busList = $system->menuWhereTerr ($business->getAllBusinessListModel(),$business);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$busList);
    }
    //查询证书负责人信息
    public function getBusinessHeadDetails(Request $request,User $user,SystemBusiness $business)
    {
        $id = $request->get ('id');

        $str = $business->getWhereIdDataModel($id);

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$user->getIdUserRandInfo($str));

    }

    //企业证书表单

    /**
     * @param \app\Request $request
     * @param \app\service\System $system
     * @param \app\model\SystemDynamicFrom $from
     * @param \app\service\User $userService
     * @param \app\model\SystemDynamicFromField $systemDynamicFromField
     * @param \app\model\SystemFieldPower $systemFieldPower
     * @param \app\model\User $user
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPersonEnterpriseCertificateFrom(
        Request $request,
        System $system,
        SystemDynamicFrom $from,
        \app\service\User $userService,
        SystemDynamicFromField $systemDynamicFromField,
        SystemFieldPower $systemFieldPower,
        User $user
    ){
        $aliasId = $request->get('aliasId');

        if (empty($aliasId)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //获取该模板id
        $fromId = $from->getFromId($aliasId);

        //获取当前用户字段权限
        $fieldData = $userService->userFieldPower ($user,$fromId,$request->get ('user_login_id'));

        //获取模板自定义字段详情
        $fieldList = $systemDynamicFromField->getTmpTrendsFieldList($fromId);

        //获取模板字段权限id
        $data = $system->powerPoint($fieldList,array_values($fieldData),true);

        databaseField::$zsbl_from['custom'] = $data;

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$data);
    }



    //企业证书提交
    public function addEnterpriseCertificate(
        Certificate                   $certificate,
        Request                       $request,
        OrderEnterpriseCertificateBusiness $orderBu,
        User $user,
        Gateway $gateway,
        \app\model\UserMessage $message,
        OrderLog $orderLog,
        Certificate $certificateSer,
        UnitInfo $unit,
        Image $image
    ){
        $param = $certificateSer->splitCer($request->post());
//        $information_file = request()->file('information_file');
//        $contract_file = request()->file('contract_file');
        $uid = $request->param ('user_login_id');

        //销售时间
        $param['sale_date'] = '';
        //收证部门收证人
//        $param['get_uid'] = $uid;
//        $param['get_org'] = $user->getUidOrgId($uid);

        //部门处理
        if (isset($param['get_org'])){
            $get_org = explode (',',$param['get_org']);
            $param['get_org'] = $get_org[count($get_org)-1];
        }
        if (isset($param['out_org'])){
            $out_org = explode (',',$param['out_org']);
            $param['out_org'] = $out_org[count($out_org)-1];
        }

        //判断是否提交注册单位
        if (!empty($param['reg_unit'])){
            //注册单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['reg_unit'],
                'type'=>$this->regUnit
            ]);
        }
        //判断是否提交注册单位
        if (!empty($param['unit_reg_title'])){
            //注册单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['unit_reg_title'],
                'type'=>$this->regUnit
            ]);
        }

        //判断是否提交聘用单位
        if (!empty($param['employ_unit_title'])){
            //聘用单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['employ_unit_title'],
                'contacts'=>$param['employ_unit_name'],
                'mobile'=>$param['employ_unit_mobile'],
                'type'=>$this->employUnit
            ]);
        }

        //判断是否提交出证单位
        if (!empty($param['out_org'])){
            //出证单位不为空 同步单位到单位资料库
            $unit->addDataModel ([
                'title'=>$param['out_org'],
                'type'=>$this->pushUnit
            ]);
        }

//        //计算该订单业绩
//        $param['performance'] = $param['sale_price']-$param['cost_price']?:0;

        //业绩归属人
        $param['performance_uid'] = $uid;
        if (!empty($param['out_uid']) && !empty($param['performance_uid'])){
            $param['performance_uid'] .= ',' . $param['out_uid'];
        }
        $param['submit_id'] = $uid;
        Db::startTrans();
        try {

            Validate(\app\validate\Certificate::class)->scene ('enterpriseCert')->check ($param);
//
//            Validate(\app\validate\Certificate::class)->scene ('file')->check ([
//                'information_file'=>$information_file,
//                'contract_file'=>$contract_file
//            ]);

            $param['certificate_code'] = $certificate->CertificateCodeCreate ('QYZS');

            //上传资料
            if (isset($param['information_file'])){
                //$param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);
                $array = $image->handle($param['information_file'],'information_file','information_file_name');
                $param['information_file'] = $array['information_file'];
                $param['information_file_name'] = $array['information_file_name'];
            }
            //上传合同
            if (isset($param['contract_file'])){
                //$param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
                $array = $image->handle($param['contract_file'],'contract_file','contract_file_name');
                $param['contract_file'] = $array['contract_file'];
                $param['contract_file_name'] = $array['contract_file_name'];
            }

            //添加证书办理
            $data = $orderBu->addDataModel($param);

            //添加操作日志
            $orderLog->addDataModel([
                'submit_id'=>$uid,
                'message'=>message::$ORDER_SHENGCHENG,
                'type'=>1,
                'order_company_id'=>$data['id'],
                'certificate_code'=>$data['certificate_code']
            ]);
            //添加消息列表
            $messages = $message->addOrderBusinessModel($data['certificate_code'],$param['responsibility_uid'],$uid,$data['id']);
            //发送消息推送
            $gateway->sendToUid($param['responsibility_uid'],json_encode ($messages));

            Db::commit();
        }catch (ValidateException | \Exception $e){
            Db::rollback();
            return ReJson (message::$ERROR_CODE,$e->getMessage ());
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }
}